//声明函数        执行器   『同步回调』

function Promise(executor) {
    //设置实例对象的属性
    this.PromiseState = 'pending';
    this.PromiseResult = undefined;
    this.callbacks = [];

    //声明函数
    const success = (value) => {
        //修改状态为成功  PromiseState
        this.PromiseState = 'fulfilled';
        //设置成功的结果值 PromiseResult
        this.PromiseResult = value;
        //调用回调
        if (this.callbacks.length > 0) {
            this.callbacks.forEach(cbObj => {
                //执行成功的回调
                cbObj.ok(value);
            })
        }
    }

    const fail = (reason) => {
        //修改状态为失败  PromiseState
        this.PromiseState = 'rejected';
        //设置成功的结果值 PromiseResult
        this.PromiseResult = reason;
        //调用回调
        if (this.callbacks.length > 0) {
            this.callbacks.forEach(cbObj => {
                //执行成功的回调
                cbObj.ng(reason);
            })
        }
    }

    try {
        //调用执行器函数
        executor(success, fail);
    } catch (e) {
        //调用 fail 函数
        fail(e);
    }
}

Promise.prototype.then = function (onFulfilled, onRejected) {
    //判断 成功
    if (this.PromiseState === 'fulfilled') {
        onFulfilled(this.PromiseResult);
    }

    //失败
    if (this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult);
    }

    //pending 
    if (this.PromiseState === 'pending') {
        //保存回调
        this.callbacks.push({
            ok: function (v) {
                //成功
                onFulfilled(v);
            },
            ng: function (r) {
                //失败
                onRejected(r);
            }
        })

    }
}




//覆盖全局的 alert
// function alert(){
//     console.log(123);
// }

//为实例对象添加属性
// function Person(age){
//     this.age = age;
// }
// let me = new Person(18);

